'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: builtin_provider_manager.py
* @Time: 2025/9/22
* @All Rights Reserve By Brtc
'''
import os.path

import yaml
from injector import singleton, inject
from pydantic import BaseModel, Field
from internal.core.tools.builtin_tools.entities.provider_entity import Provider, ProviderEntity


@inject
@singleton
class BuiltinProviderManager(BaseModel):
    """服务提供商工厂类"""
    provider_map:dict[str, Provider] = Field(default_factory=dict)


    def _get_provider_tool_map(self):
        """项目初始化的时候获取服务提供商，工具映射关系并填充到provider_tool_map"""
        # 1、检测provider_tool_map是否为空
        if self.provider_map:
            return
        # 2、获取当前文件所在的路径
        current_path = os.path.abspath(__file__)
        provider_path = os.path.dirname(current_path)
        provider_yaml_path = os.path.join(provider_path, 'providers.yaml')

        #3、读取provider.yaml数据
        with open(provider_yaml_path, encoding="utf-8") as f:
            provider_yaml_data = yaml.safe_load(f)

        #4、循环遍历所有的提供商
        for  idx , provider_data in enumerate(provider_yaml_data):
            provider_entity = ProviderEntity(**provider_data)
            self.provider_map[provider_entity.name] = Provider(
                name = provider_entity.name,
                position = idx+1,
                provider_entity = provider_entity
            )


    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._get_provider_tool_map()


    def get_provider(self, provider_name:str)->Provider:
        """根据传递的服务商名称来获取服务商"""
        return self.provider_map.get(provider_name)


    def get_providers(self)->list[Provider]:
        """获取所有 服务商列表"""
        return list(self.provider_map.values())


    def get_provider_entities(self)->list[ProviderEntity]:
        """获取所有服务商提供者信息"""
        return [provider.provider_entity for provider in self.provider_map.values()]


    def get_tool(self, provider_name:str, tool_name:str):
        """根据服务商和工具名称获取特定的工具实体"""
        provider = self.get_provider(provider_name)
        if provider is None:
            return None
        else:
            return provider.get_tool(tool_name)